package com.etb.wisdom.eframe.framework.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.etb.core.service.ETBService;
import com.etb.core.utils.SequenceUtil;
import com.etb.web.eui.tree.TreeNode;
import com.etb.web.eui.tree.TreeNode.State;
import com.etb.wisdom.eframe.framework.service.AppMenuService;
import com.etb.wisdom.eframe.model.AppMenu;

@Service
public class AppMenuServiceImpl extends ETBService implements AppMenuService {

	@Override
	public void save(AppMenu menu) {
		service.save(menu);
		if(StringUtils.isBlank(menu.getUplevelid())) {
			menu.setAppmenuseq(menu.getId());
		} else {
			AppMenu uplevelMenu = new AppMenu();
			uplevelMenu.setId(menu.getUplevelid());
			service.extend(uplevelMenu);
			menu.setAppmenuseq(SequenceUtil.generateNewSequence(uplevelMenu.getAppmenuseq(), menu.getId()));
		}
		service.save(menu);
	}
	
	public List<TreeNode> getTreenode(String id, String nodeType) {
		List<TreeNode> treedata = new ArrayList<TreeNode>();
		if(StringUtils.isBlank(id)) {
			TreeNode treenode = new TreeNode(TREENODEID_ROOT, TREENODENAME_ROOT);
			treenode.put("nodeType", TREENODETYPE_ROOT);
			treenode.setState(State.closed.toString());
			treenode.setIconCls("icon-root");
			treedata.add(treenode);
		} else {
			AppMenu menuTemplate = new AppMenu();
			if(id.equals(TREENODEID_ROOT)) {
				menuTemplate.setMenulevel("1");
			} else if(TREENODETYPE_MENU.equals(nodeType)) {
				menuTemplate.setUplevelid(id);
			}
			List<AppMenu> menus = service.query(menuTemplate, "sortno", "asc", "createTime", "desc");
			for(AppMenu menu: menus) {
				TreeNode treenode = new TreeNode(menu.getId(), menu.getMenuname());
				treenode.put("nodeType", TREENODETYPE_MENU);
				treenode.put("menuLevel", menu.getMenulevel());
				treenode.setState(State.closed.toString());
				treenode.setIconCls("icon-menu");
				treedata.add(treenode);
			}
		}
		return treedata;
	}
}
